#!/usr/bin/env python
# -*- coding: UTF-8 -*-
#__email__ = "wjx010107@163.com"
#__author__ = "weijinxing"

from __future__ import division
from django import forms
from django.shortcuts import render_to_response
from django.http  import  HttpResponse,HttpResponseRedirect,Http404
from django.contrib.auth.models import User,Permission,Group
from django.contrib.auth import authenticate, login
from django.contrib.auth import logout
from django.template import RequestContext
from api_salt import saltAPI
from js_data import get_json
from django.contrib.auth.decorators import login_required,permission_required
import simplejson as json
from django.template.context_processors import csrf
from django.views.decorators.csrf import csrf_protect,csrf_exempt
import os,datetime,time
import urllib
from atsystem.settings import FILEPATH,CMDLOG,ROOTPATH,GROUPPATH,ACCKEYPATH,DENKEYPATH,REJKEYPATH,PREKEYPATH
from utils import T_count,U_count,M_count,MG_count,G_count
import yaml
from models import Mgroup,Minions,Calendar,Minionstats,Functions
from djcelery.models import CrontabSchedule,PeriodicTask,IntervalSchedule,PERIOD_CHOICES
from djcelery import loaders
import importlib
import commands



class UserForm(forms.Form):
    username = forms.CharField()
    password = forms.CharField(widget=forms.PasswordInput)

class ChPass(forms.Form):
    password = forms.CharField(widget=forms.PasswordInput)
    cfpassword = forms.CharField(widget=forms.PasswordInput)


class UserAdd(forms.Form):
    u_name = forms.CharField( label = "username",max_length = 30)
    email = forms.EmailField(label = "Email",)
    password = forms.CharField(label = "password",widget = forms.PasswordInput,)
    cfpassword = forms.CharField(label = "confirmed_pass",widget = forms.PasswordInput,)
    

class MgroupAdd(forms.Form):
    mg_name = forms.CharField( label = "mgroupname",max_length = 30)
    comment = forms.CharField( label = "comment",max_length = 100)

class GroupAdd(forms.Form):
    g_name = forms.CharField( label = "groupname",max_length = 30)

@csrf_protect
def login_at(req):
    if req.method == "POST":
        uf = UserForm(req.POST)
        if uf.is_valid():
            username = uf.cleaned_data['username']
            password = uf.cleaned_data['password']
#            print username ,password
            req.session['username'] = username
            user = authenticate(username = username,password = password)
#            perms = user.get_all_permissions()
            if user is not None:
                if user.is_active:
                    login(req,user)
                    return HttpResponseRedirect('/admin/')
                else:
                    return HttpResponse("user is disable")   
            else:
                return HttpResponseRedirect('/login/')
    else:
        uf = UserForm()
    return render_to_response('login.html',{'uf':uf},context_instance=RequestContext(req))


@login_required(login_url='/login/')
def admin(req):
    username = req.session.get('username','anybody')
    user_per=int(User.objects.filter(is_active=False).count()/User.objects.count()*100)
    host_num={}
    host_num['acc_num'] = Minionstats.objects.get(keyname='acc_key').keynum
    host_num['den_num'] = Minionstats.objects.get(keyname='den_key').keynum
    host_num['rej_num'] = Minionstats.objects.get(keyname='rej_key').keynum
    host_num['pre_num'] = Minionstats.objects.get(keyname='pre_key').keynum
    host_num['all_num'] = Minionstats.objects.get(keyname='all_key').keynum
    host_num['all_group'] = MG_count
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    p_group=p_user.groups.all()
    mgroups=Mgroup.objects.all()
    minions=Minions.objects.all()
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    return render_to_response('admin.html',{'t_count':T_count,'username':username,'user_per':user_per,'c_count':C_count,'p_user':p_user,'p_group':p_group,'minions':minions,'mgroups':mgroups,'perms':perms,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'host_num':host_num})





@login_required(login_url='/login/')
@permission_required('auth.add_user')
def add_atuser(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    response = HttpResponse()
    if req.method == "POST":
        af = UserAdd(req.POST)
        if af.is_valid():
            u_name = af.cleaned_data['u_name']
            email = af.cleaned_data['email']
            password = af.cleaned_data['password']
            cfpassword = af.cleaned_data['cfpassword']
            if password and cfpassword and password != cfpassword:
                response.write("<script language='javascript'>window.onload=function() {alert('sucess')}</script>")
            else:
                print u_name
                user = User.objects.create_user(username=u_name,email=email,password= password)
                user.save()
                return HttpResponseRedirect('/admin/account/')
        else:
            return HttpResponse("add failed")
    else:
        af = UserAdd()    
    return render_to_response('useradd.html',{'t_count':T_count,'username':username,'c_count':C_count,'perms':perms,'af':af,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count},context_instance=RequestContext(req))


@login_required(login_url='/login/')
@permission_required('auth.delete_user')
def user_del(req,name):
#    name = req.GET.get('name')
#    print name
    _user = User.objects.filter(username=name)
    if _user and _user.values()[0]['username'] != 'admin':
        _user.delete()
    return HttpResponseRedirect("/admin/account/")



@login_required(login_url='/login/')
def logout_at(req):
    logout(req)
    uf = UserForm()
#    return render_to_response('logout.html',{})
    return HttpResponseRedirect("/login/")

@permission_required('auth.delete_user')
@login_required(login_url='/login/')
def account(req):
    users = User.objects.all()
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    return render_to_response('account.html',{'t_count':T_count,'users':users,'username':username,'c_count':C_count,'perms':perms,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})



@permission_required('auth.delete_user')
@login_required(login_url='/login/')
def group(req):
    groups = Group.objects.all()
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    return render_to_response('group.html',{'t_count':T_count,'groups':groups,'c_count':C_count,'username':username,'perms':perms,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})


@login_required(login_url='/login/')
@permission_required('auth.add_group')
def add_group(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    response = HttpResponse()
    if req.method == "POST":
        gf = GroupAdd(req.POST)
        if gf.is_valid():
            g_name = gf.cleaned_data['g_name']
            group = Group.objects.create(name=g_name)
            group.save()
            return HttpResponseRedirect('/admin/groups/')
        else:
            return HttpResponse("add failed")
    else:
        gf = GroupAdd()
    return render_to_response('groupadd.html',{'t_count':T_count,'username':username,'c_count':C_count,'perms':perms,'gf':gf,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count},context_instance=RequestContext(req))



@login_required(login_url='/login/')
def groupinfo(req,name):
    permissions = Permission.objects.all()
    groups = Group.objects.all()
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    user=[]
#    name = req.GET.get('name')
    if  p_user.is_superuser :
        user = User.objects.get(username=username)
        has_pers=user.get_all_permissions()
        group = Group.objects.get(name=name)
        for u in  User.objects.all():
            if u not in group.user_set.all():
                users.append(u)
#        u_in_g = group.user_set.all()
        return render_to_response('group_profile.html',{'t_count':T_count,'users':users,'c_count':C_count,'group':group,'has_pers':has_pers,'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'permissions':permissions,'groups':groups})
    else:
        raise Http404()


@login_required(login_url='/login/')
@permission_required('auth.delete_group')
def group_del(req,name):
#    name = req.GET.get('name')
#    print name
    group = Group.objects.filter(name=name)
    if group:
        group.delete()
    return HttpResponseRedirect("/admin/groups/")



@login_required(login_url='/login/')
@permission_required('auth.change_group')
@csrf_exempt
def update_groupinfo(req):
    arraydata=json.loads(req.POST['arraydata'])
    groupname=arraydata[0]
    inuser=arraydata[1].split(",")
    g=Group.objects.get(name=groupname)
    old_inuser=[]
    for us in g.user_set.all():
        old_inuser.append(us.username)
        if us.username in inuser:
            pass
        elif us.username not in inuser:
            g.user_set.remove(us)
    for nus in inuser:
        if nus not in old_inuser:
            g.user_set.add(User.objects.get(username=nus))
    response=HttpResponse()
    response.write(arraydata)
    return response



@login_required(login_url='/login/')
def usercalendar(req,name):
#    users = User.objects.all()
    permissions = Permission.objects.all()
    groups = Group.objects.all()
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
#    name=req.GET.get('name')
    if name == username or p_user.is_superuser :
        user = User.objects.get(username=name)
        has_pers=user.get_all_permissions()
        calendars=Calendar.objects.filter(user_id=User.objects.get(username=username).id).values()
        print calendars
        for cal in calendars:
            print cal['title']

        return render_to_response('cal.html',{'t_count':T_count,'user':user,'c_count':C_count,'calendars':calendars,'has_pers':has_pers,'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'permissions':permissions,'groups':groups})
    else:
        raise Http404()




@login_required(login_url='/login/')
@csrf_exempt
def caladd(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    arraydata=json.loads(req.POST['arraydata'])
    user_id=User.objects.get(username=username).id
    title=arraydata[0]
    start=arraydata[1]
    end=arraydata[2]
    allDay=arraydata[3]
    cal=Calendar.objects.create(title=title,start=start,end=end,allDay=allDay,user_id=user_id)
    cal.save()
    #print start
    #print end
    return render_to_response('cal.html',{'t_count':T_count,'user':user,'has_pers':has_pers,'c_count':C_count,'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'permissions':permissions,'groups':groups})
    #response=HttpResponse()
    #response.write(arraydata)
    #return response


@login_required(login_url='/login/')
def calview(req):
    username = req.session.get('username','anybody')
    cal=Calendar.objects.filter(user_id=User.objects.get(username=username).id)
    cals=[]
    for item in cal.values():
        cals.append(item)
    encodejson=json.dumps(cals)
    decodejson=json.loads(encodejson)
    response=HttpResponse()
    response.write(encodejson)
    return response









@login_required(login_url='/login/')
def userinfo(req,name):
    permissions = Permission.objects.all()
    groups = Group.objects.all()
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    if name == username or p_user.is_superuser :
        user = User.objects.get(username=name)
        has_pers=user.get_all_permissions()
    
        return render_to_response('user_profile.html',{'t_count':T_count,'user':user,'p_user':p_user,'c_count':C_count,'has_pers':has_pers,'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'permissions':permissions,'groups':groups})
    else:
        raise Http404()        



@login_required(login_url='/login/')
@csrf_exempt
def update_userinfo(req):
    arraydata=json.loads(req.POST['arraydata'])
    username=arraydata[0]
    sess_username = req.session.get('username','anybody')
    u=User.objects.get(username=username)
    su=User.objects.get(username=sess_username)
    email=arraydata[1]
    if u.is_superuser or su.is_superuser:
        active=arraydata[2]
        superuser=arraydata[3]
        group=arraydata[4]
        permission=arraydata[5]
        print str(active)
        print str(superuser)
        print str(u.is_active)
        print str(u.is_superuser)
        if email == u.email:
            pass
        else:
            u.email = email
            u.save()
        if str(active) == str(u.is_active):
            pass
        else:
            if str(active) == 'True':
	        u.is_active = True
                u.save()
            else:
                u.is_active = False
                u.save()
        if str(superuser) == str(u.is_superuser):
            pass
        else:
            if str(superuser) == 'True':
                u.is_superuser = True
                u.save()
            else:
                u.is_superuser = False
                u.save()
        if group is None:
            pass
        else:
            g=Group.objects.get(name=group)
            u.groups.add(g)
        if permission is None:
            pass
        else:
            for name in permission:
                print name
                pers=Permission.objects.get(name=name)
                u.user_permissions.add(pers)
                print u.username
    else:
        if email == u.email:
            pass
        else:
            u.email = email
            u.save()

    response=HttpResponse()
    response.write(arraydata)
    return response

def change_pass(req,name):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    if req.method == "POST":
        cf = ChPass(req.POST)
        if cf.is_valid():
#            oldpassword = req.POST.get('oldpassword')
#            user = authenticate(username=uname,password=oldpassword)
            password=req.POST.get('password')
            cfpassword=req.POST.get('cfpassword')
            user = User.objects.get(username=name)
            if user is not None and user.is_active and password == cfpassword:
                password=req.POST.get('password')
                newuser = User.objects.get(username__exact=name)
                newuser.set_password(password) 
                newuser.save()
                return render_to_response('changepass.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'cf':cf,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'changesuccess':True},context_instance=RequestContext(req))
            else:
                return render_to_response('changepass.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'cf':cf,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'notmatch':True},context_instance=RequestContext(req))
        else:
            return render_to_response('changepass.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'cf':cf,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'changefailed':True},context_instance=RequestContext(req))
    else:
        cf = ChPass()
    return render_to_response('changepass.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'cf':cf,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count},context_instance=RequestContext(req))





@login_required(login_url='/login/')
def update_hosts_list(req):
    os.system("ls /home > /tmp/update.log")
    sapi = saltAPI()
    params = {'client':'local', 'fun':'grains.item', 'tgt':'*','arg1':'id','arg2':'osfinger','arg3':'productname','arg4':'nodename','arg5':'ipv4'}
    minions = sapi.saltCmd(params)[0].values()
    for minion in minions:
	print minion['ipv4']
        jud = Minions.objects.filter(minion_id=minion['id'])
        if not jud.values():
            m=Minions(minion_id=minion['id'],os_type=minion['osfinger'],productname=minion['productname'],ipaddr=minion['ipv4'][0],hostname=minion['nodename'])
            m.save()
        else:
            pass
            print 'cunzaile'
    return HttpResponseRedirect("/admin/hosts/")


@login_required(login_url='/login/')
def host_resource(req,host):
    username = req.session.get('username','anybody')
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    funs=['disk.usage','status.meminfo','status.cpustats']
    sapi = saltAPI()
    for fun in funs:
        params = {'client':'local', 'fun':fun, 'tgt':host}
        if fun == 'disk.usage':
            diskinfo={}
            for k,v in sapi.saltCmd(params)[0][host].items():
                diskinfo[k]=v['capacity']
           
            dnum=len(diskinfo.keys())
            pl0={}
            pl1={}
            pl2={}
            if dnum <= 6:
                for k0 in diskinfo.keys()[:]:
                    pl0[k0]=diskinfo[k0]
            elif 6 < dnum <= 12:
                for k0 in diskinfo.keys()[:6]:
                    pl0[k0]=diskinfo[k0]
                for k1 in diskinfo.keys()[6:12]:
                    pl1[k1]=diskinfo[k1]
            elif dnum > 4:
                for k0 in diskinfo.keys()[:6]:
                    pl0[k0]=diskinfo[k0]
                for k1 in diskinfo.keys()[6:12]:
                    pl1[k1]=diskinfo[k1]
                for k2 in diskinfo.keys()[12:]:
                    pl2[k2]=diskinfo[k2]
             
        elif fun == 'status.meminfo':
            meminfo=sapi.saltCmd(params)[0].values()[0]
            memtotal=meminfo['MemTotal']['value']
            memfree=meminfo['MemFree']['value']
            pmused=(1.00-round((int(memfree)/int(memtotal)),2))*100
            swaptotal=meminfo['SwapTotal']['value']
            swapfree=meminfo['SwapFree']['value']
            vmused=(1.00-round((int(swapfree)/int(swaptotal)),2))*100
        else:
            cpuinfo=sapi.saltCmd(params)[0].values()[0]['cpu']
	    cinfo={}
            for k in cpuinfo.keys():
                cinfo[k]=int(cpuinfo[k])
#    print diskinfo,pmused
#    print dnum ,pl0,pl1,pl2
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)
    return render_to_response('hresource.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'dnum':dnum,'pl0':pl0,'pl1':pl1,'pl2':pl2,'pmused':pmused,'vmused':vmused,'cinfo':cinfo,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})


@login_required(login_url='/login/')
def hosts_list(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    mgroups=Mgroup.objects.all()
#    minions=Minions.objects.all()
    minions=Minions.objects.order_by("-cs_stat")
    functions=Functions.objects.all()
    return render_to_response('hosts.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'minions':minions,'mgroups':mgroups,'functions':functions,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})




@login_required(login_url='/login/')
@csrf_exempt
def host_to_mgroup(req):
    arraydata=json.loads(req.POST['arraydata'])
    print arraydata
    d_mgroup = arraydata[-1]
    print d_mgroup
    gid=Mgroup.objects.filter(mg_name=d_mgroup).values()[0]['id']
    print gid
    hostlist=arraydata[:-1]
    print hostlist
#    g1=Mgroup.objects.filter(mg_name=d_mgroup)
    for host in hostlist:
        m1=Minions.objects.get(minion_id=host)
        m1.mgroup.add(gid)
        print "db add "
    sm1=open(GROUPPATH)
    ry=yaml.load(sm1)
    sm1.close()
    host_str=','.join(hostlist)
    print host_str
    host_str=host_str.encode('utf-8')+','
    for host in hostlist:
        hostck=host.encode('utf-8')+','
        print hostck
        if hostck in ry['nodegroups'][d_mgroup]:
            host_str=host_str.replace(hostck,'')
    data=ry['nodegroups'][d_mgroup]+host_str.encode('utf-8')
#    ry['nodegroups'][d_mgroup]='L@'+','.join(hostlist)+','
    print data
    ry['nodegroups'][d_mgroup]=data
    sm2=open(GROUPPATH,'w')
    yaml.dump(ry,sm2)
    sm2.close()
    res=str("恭喜！添加成功")
    response=HttpResponse()
    response.write(res)
    return response

#    return HttpResponseRedirect("/admin/hosts/")




@login_required(login_url='/login/')
@csrf_exempt
def shortfun(req):
    arraydata=json.loads(req.POST['arraydata'])
    arg = arraydata[-1]
    funname = arraydata[-2]
    #gid=Mgroup.objects.filter(mg_name=d_mgroup).values()[0]['id']
    hostlist=arraydata[:-2]
    sapi = saltAPI()
    res = ''
    for host in hostlist:
        if arg == 'none':
            params = {'client':'local','fun':funname,'tgt':host}
        else:
            params = {'client':'local','fun':funname,'tgt':host,'arg1':arg}
        data = sapi.saltCmd(params)[0][host]
        res = res+str(host)+' :'+str(data)+'<br>'

    
    res=str(res)
    response=HttpResponse()
    response.write(res)
    return response












@login_required(login_url='/login/')
@csrf_exempt
def host_exec(req):
    response=HttpResponse()  
    mkSetInfo = json.loads(req.POST['arraydata'])
    #print mkSetInfo[-1]
    if mkSetInfo[-1] == "_mgroup":
        print "Is group"
        print mkSetInfo[:-1]
        h_list=[]
        for g in mkSetInfo[:-1]:
            for h in Minions.objects.filter(mgroup=Mgroup.objects.get(mg_name=g).id):
                if h.minion_id not in h_list:
                    h_list.append(h.minion_id)
        #h_set=set(h_list)
        dict = {'data':h_list}
    else:
        print 'No group'
        dict = {'data':mkSetInfo}
    #print dict['data']
    host = dict['data'][0]
    sapi = saltAPI()
    res = ''
    for host in dict['data']:
        #print host
        type(host)
        params = {'client':'local','fun':'test.ping','tgt':host}
        data = sapi.saltCmd(params)[0][host]
        res = res+str(host)+' :'+str(data)+'\n'
    
    response.write(res)
    return response
    

@login_required(login_url='/login/')
@csrf_exempt
def file_copy(req):
#    cpinfo=req.GET.get('cpinfo')
    hosts = req.GET.get('cpinfo')
    response = HttpResponse()
#    dstpath = FILEPATH+os.path.sep+'soft_and_conf'
    cp_file_root=FILEPATH
    file_dict=get_json(cp_file_root,list_dir=[])
    #file_dict=[{'open':'true','name':'root','children':json_d}]
#    file_dict = {}
#    files = os.listdir(FILEPATH)
#    for file in files:
#        if os.path.isfile(FILEPATH+os.path.sep+file):
#
#            file_dict[file]=datetime.datetime.fromtimestamp(os.path.getmtime(FILEPATH+os.path.sep+file)).strftime("%H:%M:%S %Y-%m-%d")
    hosts_list = hosts.split(",")
    #print file_dict
    #print hosts
    return render_to_response('filecp.html',{'file_dict':file_dict,'hosts':hosts})


@login_required(login_url='/login/')
@csrf_exempt
def cp_exec(req):
    arraydata=json.loads(req.POST['arraydata'])
    res=''
    if len(arraydata) < 3 or arraydata[-1] == '':
        res='you must choice a script or input the path!!!!'
    else:

        path=arraydata[-1]
        hosts=arraydata[0].split(",")
        h_list=[]
        if hosts[-1] == '_mgroup':
            print 'Is group'
            for g in hosts[:-1]:
                for h in Minions.objects.filter(mgroup=Mgroup.objects.get(mg_name=g).id):
                    if h.minion_id not in h_list:
                        h_list.append(h.minion_id)
            hosts=h_list
        else:
            print 'No group'
            hosts=hosts
        script=arraydata[-2].split('/root')[1]
        sapi = saltAPI()
        #res='ok'
        for host in hosts:
            params = {'client':'local','fun':'cp.get_file','tgt':host,'arg1':'salt:/'+script,'arg2':path}
            data = sapi.saltCmd(params)[0]
            #print type(data)
            #print data.key
            for key in data.keys():
                if data[key] == path:
                    res=res+key+"  : copy successlly"+"<br>"
                else:
                    res=res+key+"  : copy failed"+"<br>"
            #if not data[host]:
            #    res='no'
            #res=res+str(data)+"\n"
    response=HttpResponse()
    response.write(res)
    return response




@login_required(login_url='/login/')
@csrf_exempt
def exec_html(req):
    hosts = req.GET.get('exeinfo')
    hosts_list = hosts.split(",")
    return render_to_response('execmd.html',{'hosts':hosts})

@login_required(login_url='/login/')
@csrf_exempt
def exec_cmd(req):
    username = req.session.get('username','anybody')
    nowtime = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    today = datetime.datetime.now().strftime('%Y-%m-%d')
    arraydata=json.loads(req.POST['arraydata'])
    data_list=[]
    if len(arraydata) < 2 or arraydata[-1] == '':
        #data_list.append('you must choice a script or input the path!!!!')
        res='you must choice a script or input the path!!!!'
        #print data_list
    else:
        script=arraydata[-1]
        hosts=arraydata[0].split(",")
        h_list=[]
        if hosts[-1] == '_mgroup':
            print 'Is group'
            for g in hosts[:-1]:
                for h in Minions.objects.filter(mgroup=Mgroup.objects.get(mg_name=g).id):
                    if h.minion_id not in h_list:
                        h_list.append(h.minion_id)
            hosts=h_list
            print hosts
        else:
            print 'No group'
            hosts=hosts

        sapi = saltAPI()
        for host in hosts:
            params = {'client':'local','fun':'cmd.run','tgt':host,'arg1':script}
            data = sapi.saltCmd(params)
            data_list.append(data)
    
    log = open(CMDLOG+os.path.sep+today+username+'.log','a')
    log.write('\n'+'['+nowtime+'  ~#] '+script)
    log.close()
    response=HttpResponse()
    
    print data_list
    print type(data)
    response.write(data_list)
    return response



@login_required(login_url='/login/')
@csrf_exempt
def softwarein(req):
    hosts = req.GET.get('info')
    hosts_list = hosts.split(",")
    soft_list = []
    softs = os.listdir(ROOTPATH)
    for soft in softs:
#        if os.path.isdir(ROOTPATH+os.path.sep+soft):
        if os.path.isdir(ROOTPATH+os.path.sep+soft) and commands.getstatusoutput("ls "+ROOTPATH+os.path.sep+soft+os.path.sep+"*.sls")[0] == 0:

            soft_list.append(soft)
#    soft_list.remove(os.path.split(FILEPATH)[-1])
    return render_to_response('insoftware.html',{'hosts':hosts,'soft_list':soft_list})

@login_required(login_url='/login/')
@csrf_exempt
def in_software(req):
    arraydata=json.loads(req.POST['arraydata'])
    print arraydata
    data_list=[]
    if len(arraydata) < 2 or arraydata[-1] == '':
        res='you must choice a soft or input the path!!!!'
    else:
        soft=arraydata[-1]
        hosts=arraydata[0].split(",")
        h_list=[]
        if hosts[-1] == '_mgroup':
            print 'Is group'
            for g in hosts[:-1]:
                for h in Minions.objects.filter(mgroup=Mgroup.objects.get(mg_name=g).id):
                    if h.minion_id not in h_list:
                        h_list.append(h.minion_id)
            hosts=h_list
            print hosts
        else:
            print 'No group'
            hosts=hosts

        sapi = saltAPI()
        for host in hosts:
            params = {'client':'local','fun':'state.sls','tgt':host,'arg1':soft}
            data = sapi.saltCmd(params)
            data_list.append(data)

    response=HttpResponse()
    print data_list
    print type(data)
    response.write(data_list)
    return response


@login_required(login_url='/login/')
def mgroup_list(req):
#    stream1=open(GROUPPATH)
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
#    resyaml=yaml.load(stream1)
#    stream1.close()
#    mgroups=resyaml['nodegroups'].keys()
    mgroups=Mgroup.objects.all()
    return render_to_response('mgrouplist.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'mgroups':mgroups,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})


@login_required(login_url='/login/')
def add_mgroup(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    if req.method == "POST":
        mgf = MgroupAdd(req.POST)
        if mgf.is_valid():
            mg_name = mgf.cleaned_data['mg_name']
            comment = mgf.cleaned_data['comment']
            mg_name = mg_name.encode('utf-8')
            if not mg_name:
                response.write("<script language='javascript'>window.onload=function() {alert('sucess')}</script>")
            else:
                print mg_name
		sm1=open(GROUPPATH)
                ry=yaml.load(sm1)
                sm1.close()
                mlist=''
                ry['nodegroups'][mg_name]='L@'+mlist
                sm2=open(GROUPPATH,'w')
                yaml.dump(ry,sm2)
                sm2.close()
                mg1 = Mgroup(mg_name=mg_name,comment=comment)
                mg1.save()
                return HttpResponseRedirect('/admin/mgroups/')
        else:
            return HttpResponse("add failed")
    else:
        mgf = MgroupAdd()
    return render_to_response('mgroupadd.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'username':username,'mgf':mgf,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count},context_instance=RequestContext(req))


@login_required(login_url='/login/')
def mg_del(req,name):
#    name = req.GET.get('name')
#    arraydata=json.loads(req.POST['arraydata'])
    Mgroup.objects.filter(mg_name=name).delete()
#    print arraydata
    print name
    sm1=open(GROUPPATH)
    ry=yaml.load(sm1)
    sm1.close()
    del ry['nodegroups'][name]
    sm2=open(GROUPPATH,'w')
    yaml.dump(ry,sm2)
    sm2.close()
    return HttpResponseRedirect("/admin/mgroups/")



@login_required(login_url='/login/')
def mg_profile(req,name):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
#    name=req.GET.get('name')
    mgname=Mgroup.objects.get(mg_name=name).mg_name
    comment=Mgroup.objects.get(mg_name=name).comment
    mins=Minions.objects.filter(mgroup=Mgroup.objects.get(mg_name=name).id)
    return render_to_response('mg_profile.html',{'t_count':T_count,'perms':perms,'c_count':C_count,'name':name,'mgname':mgname,'comment':comment,'mins':mins,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count},context_instance=RequestContext(req))



@login_required(login_url='/login/')
@csrf_exempt
def update_mg_profile(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)

    arraydata=json.loads(req.POST['arraydata'])
    print arraydata
    middle_val=arraydata[0]
    mg_name=arraydata[1].encode('utf-8')
    comment=arraydata[2]
    print mg_name
    print comment
    m=Mgroup.objects.get(mg_name=middle_val)
    if mg_name == m.mg_name:
        pass
    else:
        m.mg_name = mg_name
        m.save()
        sm1=open(GROUPPATH)
        ry=yaml.load(sm1)
        sm1.close()
        ry['nodegroups'][mg_name]=ry['nodegroups'][middle_val].encode('utf-8')
        del ry['nodegroups'][middle_val]
        sm2=open(GROUPPATH,'w')
        yaml.dump(ry,sm2)
        sm2.close()
    if comment == m.comment:
        pass
    else:
        m.comment = comment
        m.save()
    print arraydata[3]
    print type(arraydata[3])
    print "abcd"
    if  arraydata[3] is None:
        pass
        print "is none"
    else:
        print "is not none"
        del_host=arraydata[3]
        sm1=open(GROUPPATH)
        ry=yaml.load(sm1)
        sm1.close()
        g=Mgroup.objects.get(mg_name=middle_val)
        for dhost in del_host:
            h=Minions.objects.get(minion_id=dhost)
            h.mgroup.remove(g)
            ry['nodegroups'][mg_name]=ry['nodegroups'][mg_name].replace(dhost+',','').encode('utf-8') 
        sm2=open(GROUPPATH,'w')
        yaml.dump(ry,sm2)
        sm2.close()

    response=HttpResponse()
    response.write('update ok !!')
#    return HttpResponseRedirect("/admin/mgroups/")
    return response

def dirlist(request):
   r=['<ul class="jqueryFileTree" style="display: none;">']
   try:
       r=['<ul class="jqueryFileTree" style="display: none;">']
       d=urllib.unquote(request.POST.get('dir',FILEPATH))
       for f in os.listdir(d):
           ff=os.path.join(d,f)
           if os.path.isdir(ff):
               r.append('<li class="directory collapsed"><a href="#" rel="%s/">%s</a></li>' % (ff,f))
           else:
               e=os.path.splitext(f)[1][1:] # get .ext and remove dot
               r.append('<li class="file ext_%s"><a href="#" rel="%s">%s</a></li>' % (e,ff,f))
       r.append('</ul>')
   except Exception,e:
       r.append('Could not load directory: %s' % str(e))
   r.append('</ul>')
   return HttpResponse(''.join(r))
#   return HttpResponse('fdafdsafad')







def test(req):
    cp_file_root=FILEPATH
    json_d=get_json(cp_file_root,list_dir=[])
    file_dict=[{'open':'true','name':'root','children':json_d}]

    return render_to_response('insoftware_test.html',{"file_dict":file_dict})




@csrf_exempt
def echo(req):
    arraydata=json.loads(req.POST['arraydata'])
    print arraydata
    file = arraydata[1]
    file1=file.split('/root')[1]
    response=HttpResponse()
    response.write(file1)
    return response




@login_required(login_url='/login/')
def task_list(req):
    username = req.session.get('username','anybody')
    tady=time.strftime("%Y-%m-%d",time.localtime())
    caltmp=[]
    for cal in Calendar.objects.filter(user_id=User.objects.get(username=username).id).values():
        if cal['start'].encode('utf-8') == tady:
            caltmp.append(cal['title'])
    C_count=len(caltmp)
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    task_list = PeriodicTask.objects.all()
    return render_to_response('tasks_list.html',{'task_list':task_list,'perms':perms,'c_count':C_count,'t_count':T_count,'username':
username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count})


@login_required(login_url='/login/')
def task_del(req,ID):
    PeriodicTask.objects.get(id=ID).delete()
    return HttpResponseRedirect("/admin/tasks/")

@login_required(login_url='/login/')
def task_profile(req,ID):
    username = req.session.get('username','anybody')
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    task = PeriodicTask.objects.get(id=ID)
    crontab = CrontabSchedule.objects.all()
    interval = IntervalSchedule.objects.all()
    period_choices = [x[0] for x in PERIOD_CHOICES]
    disco_task = []
    for t  in loaders.autodiscover():
        for i in dir(importlib.import_module(t.__name__)):
            if str(getattr(importlib.import_module(t.__name__),i)).startswith('<@task'):
                disco_task.append(getattr(importlib.import_module(t.__name__),i).__name__)
    return render_to_response('task_profile.html',{'task':task,'perms':perms,'username':username,'disco_task':disco_task,'crontab':crontab,'interval':interval,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'t_count':T_count},context_instance=RequestContext(req))


@login_required(login_url='/login/')
@csrf_exempt
def update_taskinfo(req):
    arraydata=json.loads(req.POST['arraydata'])
    task_id=arraydata[0]
    is_enable=arraydata[1]
    inter_id=arraydata[2]
    cron_id=arraydata[3]
    sess_username = req.session.get('username','anybody')
    task=PeriodicTask.objects.get(id=task_id)
    if str(is_enable) == 'True':
        task.enabled = True
    else:
        task.enabled = False
    task.save()
    if str(inter_id) == 'None':
        task.interval_id = None
    else:
        task.interval_id = int(inter_id)
    task.save()
    if str(cron_id) == 'None':
        task.crontab_id = None
    else:
        task.crontab_id = int(cron_id)
    task.save()
    print task_id
    print is_enable
    print type(is_enable)
    print inter_id
    print type(inter_id)
    print cron_id
    print type(cron_id)
    response=HttpResponse()
    response.write('ok')
    return response




@login_required(login_url='/login/')
@csrf_exempt
def task_add(req):
    username = req.session.get('username','anybody')
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    crontab = CrontabSchedule.objects.all()
    interval = IntervalSchedule.objects.all()
    period_choices = [x[0] for x in PERIOD_CHOICES]
    disco_task = []
    for t  in loaders.autodiscover():
        for i in dir(importlib.import_module(t.__name__)):
            if str(getattr(importlib.import_module(t.__name__),i)).startswith('<@task'):
#                disco_task.append(getattr(importlib.import_module(t.__name__),i).__name__)
                disco_task.append(str(getattr(importlib.import_module(t.__name__),i)).split(" ")[1])
    if req.method == "POST":
        arraydata=json.loads(req.POST['arraydata'])
        tname=arraydata[0]
        if arraydata[1] == 'True':
            is_enable=1
        else:
            is_enable=0
        task=arraydata[2]
        inter_id=arraydata[3]
        if arraydata[3] == 'None':
            inter_id = None
        else:
            inter_id = int(arraydata[3])
        if arraydata[4] == 'None':
            cron_id = None
        else:
            cron_id = int(arraydata[4])
        tmodel=PeriodicTask(name=str(tname),enabled=is_enable,task=str(task),interval_id=inter_id,crontab_id=cron_id)
        tmodel.save()
        response=HttpResponse()
        response.write('Add success !!')
        return response
    return render_to_response('task_add.html',{'perms':perms,'username':username,'disco_task':disco_task,'crontab':crontab,'interval':interval,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'t_count':T_count},context_instance=RequestContext(req))




@login_required(login_url='/login/')
@csrf_exempt
def interval_add(req):
    username = req.session.get('username','anybody')
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    period_choices = [x[0] for x in PERIOD_CHOICES]
    if req.method == "POST":
        interdata=json.loads(req.POST['interdata'])
    #    print interdata
        every=int(interdata[0])
        period=str(interdata[1])
        IntervalSchedule.objects.create(every=every,period=period)
        response=HttpResponse()
        response.write('Add success !!')
        return response
    return render_to_response('interval_add.html',{'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'t_count':T_count,'period_choices':period_choices},context_instance=RequestContext(req))



@login_required(login_url='/login/')
@csrf_exempt
def crontab_add(req):
    username = req.session.get('username','anybody')
    p_user = User.objects.get(username=username)
    perms=list(p_user.get_all_permissions())
    if req.method == "POST":
        crondata=json.loads(req.POST['crondata'])
        minute=str(crondata[0])
        hour=str(crondata[1])
        dweek=str(crondata[2])
        dmouth=str(crondata[3])
        myear=str(crondata[4])
        CrontabSchedule.objects.create(minute=minute,hour=hour,day_of_week=dweek,day_of_month=dmouth,month_of_year=myear)
        response=HttpResponse()
        response.write('Add success !!')
        return response
    return render_to_response('crontab_add.html',{'perms':perms,'username':username,'u_count':U_count,'g_count':G_count,'m_count':M_count,'mg_count':MG_count,'t_count':T_count},context_instance=RequestContext(req))

